package com.jxnu.duewang.zmly.zouZhen.widget;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

/**
 * Project Zmly
 * Author Duewang
 * Time 2016/12/13 0013
 */

public class RxBus {

    private static RxBus rxbus;
    private final Subject<Object,Object> _bus;

    // PublishSubject只会把来自Observable的原始数据在订阅 (发生的时间点) 之后发射给观察者
    private RxBus(){
        _bus=new SerializedSubject<>(PublishSubject.create());
    }

    //单例RxBus
    public static RxBus getDefault(){
        if(rxbus==null){
            synchronized (RxBus.class){
                rxbus=new RxBus();
            }
        }
        return rxbus;
    }

    //发送一个新的事件
    public void post(Object object){
        _bus.onNext(object);
    }

    // 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者
    public <T> Observable<T> toObservable(Class<T> eventType){
        return _bus.ofType(eventType);
//        ofType = filter + cast
//        return bus.filter(new Func1<Object, Boolean>() {
//            @Override
//            public Boolean call(Object o) {
//                return eventType.isInstance(o);
//            }
//        }) .cast(eventType);
    }

    public Observable<Object> toObserverable() {
        return _bus;
    }

}
